/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.util;

import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

/**
 *
 * Resizable-array implementation of the <tt>List</tt> interface.  Implements
 * all optional list operations, and permits all elements, including
 * <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
 * this class provides methods to manipulate the size of the array that is
 * used internally to store the list.  (This class is roughly equivalent to
 * <tt>Vector</tt>, except that it is unsynchronized.)
 *
 * 可调整大小数组是List接口的具体实现。
 * 实现所有List可选的操作,并且允许所有元素(包括null)。 (意味着ArrayList支持所有类型,包括了null)
 * 为了进一步实现List接口的内容,ArrayList这个类提供了一些修改内部存储列表数组大小的方法。 (就是说这里有方法可以修改它的数组大小)
 * 这个类除了不同步外(线程不安全),可以近乎等价于Vector类
 *
 * <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
 * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
 * time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
 * that is, adding n elements requires O(n) time.  All of the other operations
 * run in linear time (roughly speaking).  The constant factor is low compared
 * to that for the <tt>LinkedList</tt> implementation.
 *
 * size,isEmpty,get,set,iterator,listIterator操作都是O(1)的时间复杂度。
 * add是摊销常量时间复杂度
 * 因此添加n个元素需要O(n)时间。
 * 其他操作都是粗略来说是线性时间。
 * ArrayList的常量因子是低于LinkedList类实现的
 *
 *
 * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
 * the size of the array used to store the elements in the list.  It is always
 * at least as large as the list size.  As elements are added to an ArrayList,
 * its capacity grows automatically.  The details of the growth policy are not
 * specified beyond the fact that adding an element has constant amortized
 * time cost.
 * 每一个ArrayList实例都会拥有一个capacity容量, capacity是列表中数组用来存储元素的大小
 * 它一般至少跟列表大小一样大。
 * 当元素加进ArrayList时候,列表容量就会自动增加。
 * 除了增加一个元素具有恒定的摊余时间成本这一事实之外,没有具体说明增长方案的细节。
 *
 * <p>An application can increase the capacity of an <tt>ArrayList</tt> instance
 * before adding a large number of elements using the <tt>ensureCapacity</tt>
 * operation.  This may reduce the amount of incremental reallocation.
 *
 * 一个应用可以在添加更大数字的元素之前使用ensureCapacity()增加ArrayList实例的容量。
 * 这可能会减少增量再分配的数量 奇怪
 * <p><strong>Note that this implementation is not synchronized.</strong>
 * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
 * and at least one of the threads modifies the list structurally, it
 * <i>must</i> be synchronized externally.  (A structural modification is
 * any operation that adds or deletes one or more elements, or explicitly
 * resizes the backing array; merely setting the value of an element is not
 * a structural modification.)  This is typically accomplished by
 * synchronizing on some object that naturally encapsulates the list.
 * 注意ArrayList不是线程安全的,不具备同步条件。
 * 如果多线程并发访问ArrayList,或者至少会有一个一个线程修改列表结构时候,它必须要在外部给设置synchronized(也就是并发时候一定要保证ArrayList是同步状态)
 * 一个结构性修改(添加删除一个或者多个元素、或者显式调整List大小。仅仅修改元素并不是结构性修改)
 * 这通成是通过自然封装的List某个对象上进行同步来实现的。 (除了修改元素内容外,都算结构性修改,也就是有结构性修改的时候,一定要给方法体同步,否则会出问题)
 *
 * If no such object exists, the list should be "wrapped" using the
 * {@link Collections#synchronizedList Collections.synchronizedList}
 * method.  This is best done at creation time, to prevent accidental
 * unsynchronized access to the list:<pre>
 * List list = Collections.synchronizedList(new ArrayList(...));</pre>
 * List lsit = Collections.syschonrizedList(new ArrayList()); -> 让ArrayList变成syschonrizedList
 * 如果不存在这样的对象,List应该使用封装好的syschronizedList方法
 * 这最好在创建时间完成,可以避免意外的非同步访问List
 *
 * <p><a name="fail-fast">
 * 快速失败
 * The iterators returned by this class's {@link #iterator() iterator} and
 * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:</a>
 * if the list is structurally modified at any time after the iterator is
 * created, in any way except through the iterator's own
 * {@link ListIterator#remove() remove} or
 * {@link ListIterator#add(Object) add} methods, the iterator will throw a
 * {@link ConcurrentModificationException}.  Thus, in the face of
 * concurrent modification, the iterator fails quickly and cleanly, rather
 * than risking arbitrary, non-deterministic behavior at an undetermined
 * time in the future.
 * iterator()/listIterator(int)方法将返回这个类中的可迭代的所有元素。
 * 如果在iterator()调用后,除了使用iterator结构提供的remove()、add(Object)、(增删方法外),遇到了结构性修改,
 * 这就会出现ConcurrentModificationException。
 * 因此,面对并发问题,迭代器会快速干净地失败,而不是在未来某个不确定的时间冒着任意、不确定行为的风险。
 *
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
 * as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw {@code ConcurrentModificationException} on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this
 * exception for its correctness:  <i>the fail-fast behavior of iterators
 * should be used only to detect bugs.</i>
 * 注意,迭代器的快速失败行为并不能像这样得到保证。
 * 一般来说，在存在不同步并发修改的时候很难做出强硬保证能够如此实现的。
 * 迭代器只能尽最大努力抛出ConcurrentModificationException来实现快速失败
 * 因此,编写一个依赖于这个异常的程序是错误的。
 * 快速迭代器的行为应该只用于检测bug(错误)
 *
 *  关于文档的一些地址
 * <p>This class is a member of the
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 * Java Collections Framework</a>.
 *
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see     Collection
 * @see     List
 * @see     LinkedList
 * @see     Vector
 * @since   1.2
 *
 * 1.2就出现了ArrayList
 */

/**我们可以看到ArrayList继承了AbstarctList类,并且继承了List接口、RandomAccess接口、Cloneable接口、java.io.Serializable接口
 * RandomAccess是一个标志接口,表明了ArrayList是支持快速随机访问的。
 * 在ArrayList中我们可以通过元素序号快速的获取元素对象,这个就是快速随机访问。
 * ArrayList实现了Cloneable接口,即覆盖了clone()函数,能被克隆
 * ArrayList实现了java.io.Serializable接口,这意味着ArrayList支持序列化,能通过序列化去传输。
 * */
// 一共有三种构造方法,无参(默认为10),指定容量大小,集合构造
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    //序列化ID
    private static final long serialVersionUID = 8683452581122892189L;

    /**
     * Default initial capacity.
     * DEFAULT_CAPACITY 默认的初始容量大小为10
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * Shared empty array instance used for empty instances.
     * 空数组(用于空实例),某些情况会返回一个空ArrayList,此时就会用到下面这个EMPTY_ELEMENTDATA作为Object[] = {} 返回
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     *
     * 默认大小空实例共享空数组实例
     * 我们把它从EMPTY_ELEMENTDATA区分出来是为了知道当第一个元素添加时候要增加多少容量。
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //这个是一个空数组,并不存在容量,可以当成null看待

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added. <br>
     * 存储ArrayList元素的数组缓存区
     * 这个数组缓存区的长度为ArrayList容量大小
     * 当第一杆元素被添加的时候 带有elementData的空ArrayList等同于 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 将会被扩展为 DEFAULT_CAPACITY = 10
     *
     *
     * <pre>
     * 容量变化为：10
     *           10 + 10/2 = 15
     *           15 -> 15 + 15/2 = 22
     *           22 -> 22 + 22/2 = 33
     * </pre>
     * <br>
     * -----
     *
     * 如果数组的长度设为100，而实际只放了一个元素，那就会序列化99个null元素。
     * 为了保证在序列化的时候不会将这么多null同时进行序列化，所以设置为transient
     * 保存ArrayList数据的Object[] elementData数组
     */
    // transient用来修饰成员变量(field),被transient修饰的成员变量不参与序列化的过程
    // 这个说明了elementData不参与序列化过程
    transient Object[] elementData; // non-private to simplify nested class access。 非private来简化嵌套类访问它

    /**
     * The size of the ArrayList (the number of elements it contains). <br>
     * 包含元素的个数
     *
     * @serial
     */
    private int size;

    /**
     * Constructs an empty list with the specified initial capacity.
     * ArrayList的构造器, 根据initialCapacity的容量来构造ArrayList (带初始容量参数的构造函数,用户可以在创建ArrayList对象时候自己指定集合的初始大小)
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    // 容量参数构造
    public ArrayList(int initialCapacity) {
        //如果传入的初始容量值大于0
        if (initialCapacity > 0) {
            // 定义存储Object[]数组的大小为传入的容量大小
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            // 等于0,直接 Object[] EMPTY_ELEMENTDATA = {};
            this.elementData = EMPTY_ELEMENTDATA; // 创建空数组
        } else {
            //如果小于0/其他情况就抛出异常
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten. <br>
     * 构建一个空列表，在第一次调用 {@link #add(Object)} 的时候才会将列表的容量初始化为 10
     * 我们平时用的都是这个,创建空列表了
     */
    // 无参构造,初始容量为10
    public ArrayList() {
        // 延迟分配数组空间这个，几乎底层有数组结构的集合都是这样。
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; // 这个时候是没有用到ensureCapacity的,相当于只分配了一个空数组,没有分配容量
        // 等我们向数据添加第一个元素时候,数组容量才会扩容到10.

        // ext: JDK6 new 无参构造的ArrayList对象时,是直接创建了长度10的Object[] elementData (现在可真省,无参构造先不分配空间,有需要再分个10空间,这就省了Object的字节数*10的空间,还不错)
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     * 构造一个包含指定集合的元素的列表
     * 按照它们由集合的迭代器返回的顺序
     * (传入同类型的集合去创建一个ArrayList)
     * @param c the collection whose elements are to be placed into this list   c是要传入的集合的所有元素(集合的地址)
     * @throws NullPointerException if the specified collection is null 如果传入集合为NULL就抛出空指针异常
     */
    // 集合参数构造,构造包含指定colleciton元素的列表,这些元素按照该集合的迭代器顺序返回
    public ArrayList(Collection<? extends E> c) {
        //先将集合转换为数组
        elementData = c.toArray();
        //如果elementData的长度不等于0,也就是传入的集合不为空,有元素的话
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            //由于c.toArray() 可能返回的不准确,并不一定返回Object类型的数组,所以要添加多一层判断
            if (elementData.getClass() != Object[].class) //如果返回的不是Object类型的内容
                //将原来不是Object类型的elementData数组的内容,赋值给新的Object类型的elementData数组
                elementData = Arrays.copyOf(elementData, size, Object[].class);//Arrays.copyOf(原数组,新数组大小,新数组类型)
        } else { //如果是空集合
            // replace with empty array.
            //直接用EMPTY_ELEMENTDATA代替
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }

    /**
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
     * 修剪该ArrayList实例容量为当前List的size大小,
     * 应用程序可以用这个操作最小化ArrayList实例的存储。(trimToSize相当于压缩空间,因为我们capacity一般是比size
     * 要大的,但这样会过多占用了空间,如果用trim(capacity)ToSize,就可以减少空间浪费的情况,前提是这个ArrayList基本处于不增、只删情况比较好)
     */
    public void trimToSize() {
        modCount++; //数组被更改次数增加
        //如果size<当前Object[]数组的长度
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA  //如果size为0,如果size为0就返回一个空数组
              : Arrays.copyOf(elementData, size); //如果不为0,就根据size来复制一个elementData(这样刚好能滤掉多余的空间)
        }
    }

    /**
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     *
     * 如果需要,增加ArrayList实例的容量,要确保它至少可以容纳最小容量参数指定的元素数 (就是你ArrayList空间不够,需要ensureCapacity来扩容,保证至少可以容纳最小容量,不然就溢出了)
     * ArrayList的扩容机制,ArrayList的扩容机制提高了性能
     * 如果每次只扩容一个,频繁的插入会导致频繁的拷贝,降低性能,而ArrayList的扩容机制避免了这种情况(以批量扩容)
     * 最好在 add 大量元素之前用 ensureCapacity 方法，以减少增量重新分配的次数
     * 比如一个for循环,你要在这个循环内add大量元素,就需要ensureCapacity你要添加的容量。
     * @param   minCapacity   the desired minimum capacity 所需的最小容量
     */
    public void ensureCapacity(int minCapacity) {
        //如果是true，minExpand的值为0，如果是false,minExpand的值为10
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) //最小扩展,如果elementData存储的数据不为空的(默认容量10,且空数组情况)  如果elementData不为空就扩容0,为空就扩容10
            // any size if not default element table
            ? 0 //如果数组不为空,就先不管它第一次扩容的数量,设置为0,动态扩容具体交给ensureCapacityInternal来做
            // larger than default for default empty table. It's already
            // supposed to be at default size.
            //DEFAULT_CAPACITY为10
            : DEFAULT_CAPACITY;  //这里相当于空数组第一次扩容时候,一开始我们空数组的容量是0的,所以默认每次扩容+10
        // 如果最小容量大于已有的最大容量
        // 如果需要的最小容量已经大于了最小要扩展的数量,就要进一步扩容了
        if (minCapacity > minExpand) {
            //就要显式扩容了
            ensureExplicitCapacity(minCapacity);
        }
    }

    // JDK11 移除了ensureCapacityInternal与ensureExplicitCapacity两个方法
    //1.得到最小扩容容量
    //2.通过最小容量扩容
    private void ensureCapacityInternal(int minCapacity) {
        // 这个是用来判断是否第一次添加元素的
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如果是第一次添加
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); //取最大容量与10之间进行比较
            // 为什么这么比较,因为addAll(Collection)是添加不止一个元素的,有可能会超过默认提供的10的元素
        }
        ensureExplicitCapacity(minCapacity);

    }
    // 为什么这两个方法不写在一起……
    // 判断是否需要扩容
    private void ensureExplicitCapacity(int minCapacity) {
        //修改ArrayList次数增加,因为触发了扩容,有调用到Arrays.copyOf,Object[]的具体元素数量变化 为什么modCount不写在grow里？
        modCount++;

        // overflow-conscious code

        /*
         * 第一次添加的时候，数组的长度为0，
         * 第一次添加之后，数组的长度为10
         */
        //如果最小扩容数量减去目前有的元素大小,得出来的就是后面需要扩容的大小
        // 如果要扩容的大小比原有的大小要大才可以扩容,如果要扩容数量小过原有数组大小的话肯定不行的。
        //如何触发扩容机制? 也就是最小容量大于目前对象数组长度的时候
        if (minCapacity - elementData.length > 0) {
            //调用grow方法进行扩容,grow()代表开始扩容了
            grow(minCapacity); //扩容最小需要的容量
        }
    }

    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit <br>
     * 数组要分配的最大大小
     * 一些虚拟机保留了header words(头字,就字节低位的一些标识字)在数组里
     * 尝试分配更大的数组可能会导致内存溢出OutOfMemoryError的错误 (请求数组大小超过了该虚拟机数组的长度限制)
     *
     * 为什么要减8？
     * 因为有些虚拟机会在数组种分配header words 头部字。
     * 数组有些特殊性,数组对象要额外存储数组元素在头部,少了8个长度可能与此有关
     *
     * 简单的说,有些虚拟机大于MAX_ARRAY_SIZE(Integer.MAX_VALUE - 8)的长度就容易OOM
     *
     */

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     * 增加容量，以确保它至少可以容纳最小容量参数指定的元素数。
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        
        // overflow-conscious code
        int oldCapacity = elementData.length; //oldCapacity为旧容量
        // 通过oldCapacity >> 1, 将旧容量除以一半,(位运算保证了执行效率)
        // 容量 = 旧容量 + 旧容量/2 = 旧容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1); //newCapacity为新容量
        // 1.为什么不是minCapacity+1?
        // 因为预先申请多一些容量能够避免扩容,减少了CPU执行指令的占用时间,这里使用了空间换时间的思想。

        // 2.位移运算符比那些普通运算符的运算要快很多,因为程序仅仅移动一下,不进行计算,提高了效率,节省了资源。
        // 奇偶不同, 10+10/2 = 15, 33+33/2=49 因为奇数会丢掉小数
        // 如果上面规则扩容的新容量仍然比需要的最小容量小,那么就直接按最小容量来扩容

        // 3.Redis的动态字符串和这里有相似之处。
        // 为什么Redis动态字符串扩容会有两个处理方式? 为什么大于1M么此增加1M而且有最大长度限制?
        // 使用场景的问题:
        // Redis通常用作缓存,失效时间相对较长(短几秒钟,多则几分钟,几个小时)
        // ArrayList通常在某个函数用,一般生命周期很短,出栈后就可以回收。
        // Redis最大值限制是因为通常和使用者不在同一个服务器上,需要网络进行传输,如果很大就容易超时,而Redis主任务为单线程,容易阻塞到其他任务执行。


        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        // 检查新容量是否超出了ArrayList定义的最大容量
        // 如果超出了就调用hugeCapacity()来比较minCapacity和MAX_ARRAY_SIZE
        // 如果minCapacity大于了MAX_ARRAY_SIZE,则新容量为Integer.MAX_VALUE,否则新容量大小为MAX_ARRAY_SIZE
        // 这里已经意味着正常新扩容长度已经大于了MAX_ARRAY_SIZE(Integer.MAX - 8),因此此时最大可用扩容到Integer.MAX
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            newCapacity = hugeCapacity(minCapacity);
        }

        // 将旧数组中元素拷贝到新数组中
        // minCapacity is usually close to size, so this is a win:
        // 根据新容量来拷贝一份新的Object空间替换掉原有的Object空间
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 大扩容
    private static int hugeCapacity(int minCapacity) {
        // 这里对minCapacity负值进行判断, 如果为负则OutOfMemoryError
        if (minCapacity < 0) { // overflow
            throw new OutOfMemoryError();
        }
        // 所以我们为了避免JVM数组长度问题, 应该第一次给它一个机会,先让它扩容到MAX_ARRAY_SIZE的大小,如果它真的大于了这个值,那就只能扩容到Integer.MAX了(能不OOM就不OOM,但最后大于了还是会OOM的)
        // 如果minCapacity大于MAX_ARRAY_SIZE 则是Integer.MAX_VALUE,否则为MAX_ARRAY_SIZE
        return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
    }

    /**
     * Returns the number of elements in this list.
     * 返回这个List的大小
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     * 返回List是否为空的状态,根据size判断
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns <tt>true</tt> if this list contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this list contains
     * at least one element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     * 如果列表中存在指定的元素就返回true,
     * 更正式的说,当且仅当List存在至少一个符合条件的元素(该元素不可为null,且Object o不为null,且Object o 要 equals Element e)
     * @param o element whose presence in this list is to be tested 要判断其是否存在该List的对象o
     * @return <tt>true</tt> if this list contains the specified element 如果该List存在指定的元素就返回true
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * indexOf(Object o), 返回列表中指定元素首次出现在List中的索引,如果此列表不包含该元素则返回-1
     * 更正式的说, 返回最小的索引i,
     * o!=null,get(i)!=null,o.equals(get(i))
     */
    public int indexOf(Object o) {
        // 如果传入的Object o 为null (ArrayList是可以存null的)
        if (o == null) {
            for (int i = 0; i < size; i++) //O(n)遍历数组,如果为null就返回i
                if (elementData[i]==null) //如果Object[]数组
                    return i;
        } else {
            for (int i = 0; i < size; i++) //根据o来equals比较数组中元素是否有相等的
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * Returns the index of the last occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the highest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     * 返回此列表中指定元素的最后一次出现的索引,如果此列表不包含元素,则返回-1
     * 从尾部开始遍历数组
     */
    public int lastIndexOf(Object o) {
        if (o == null) {
            for (int i = size-1; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = size-1; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
     * elements themselves are not copied.)
     * clone()会返回一个ArrayList实例的浅拷贝。 (元素自身是不会被复制的)
     *
     * @return a clone of this <tt>ArrayList</tt> instance
     * 返回一个ArrayList实例的克隆
     */
    public Object clone() {
        try {
            // ArrayList<?> 表明了泛型,支持任何非基础数据类型的类型 我们并不知道最终的<?>会是什么
            ArrayList<?> v = (ArrayList<?>) super.clone();
            // elementData为原数组的内容,size为原数组的长度
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            // 因为我们继承了Cloneable类,所以这不应该发生的
            throw new InternalError(e);
        }
    }

    /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *  以正确的顺序(从第一个到最后一个元素)返回一个包含此List中所有元素的数组。
     *
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * 返回的元素将是safe的,因为该List不会保留对它的引用。 (不是直接返回elementData这个Object[]数组,toArray()实际上是对elementData进行了Arrays.copyOf再返回的)
     * 换个说法: 这个方法必须分配一个新的数组(新的且地址不同的数组)
     * 调用者可以自由的修改返回的数组(因为跟elementData没关系了,不会有任何影响到先前list的elementData)
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     * 这个方法是数组与集合的桥梁(也就是说,你得通过Collection(List是实现了Collection的)转array,就需要通过这个toArray来实现)
     *
     * @return an array containing all of the elements in this list in
     *         proper sequence
     *         返回一个按正确顺序包含此list的所有元素的数组
     */
    public Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    /**
     * Returns an array containing all of the elements in this list in proper
     * sequence (from first to last element); the runtime type of the returned
     * array is that of the specified array.
     * If the list fits in the
     * specified array, it is returned therein.  Otherwise, a new array is
     * allocated with the runtime type of the specified array and the size of
     * this list.
     *
     * 返回一个包含所有list元素的数组(顺序从第一个到最后一个)
     * 返回的运行时类型是传入指定数组的类型。(我认为就是,你传了一个动态时的数组类型进来,这个函数给你做了数组的类型转换,不然返回的就是上一个函数的Object[]了)
     * 如果列表适合指定的数组,则返回其中(也就是类型相匹配)。
     * 否则,将使用指定数组运行时类型和此列表的大小分配一个新数组。
     * 
     * <p>If the list fits in the specified array with room to spare
     * (i.e., the array has more elements than the list), the element in
     * the array immediately following the end of the collection is set to
     * <tt>null</tt>.  (This is useful in determining the length of the
     * list <i>only</i> if the caller knows that the list does not contain
     * any null elements.)
     *
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * @return an array containing the elements of the list
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * @throws NullPointerException if the specified array is null
     *
     * 以正确的顺序返回一个包含此列表中所有元素的数组（从第一个到最后一个元素）;
     * 返回的数组的运行时类型是指定数组的运行时类型。 如果列表适合指定的数组则返回其中
     *
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        if (a.length < size) //如果传入的a小于该List的长度
            // Make a new array of a's runtime type, but my contents:
            // 新建一个运行时类型的数组
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());

        //这时候是a的长度大于size了 我们就要截断这个长度 最多只能size
        //System提供的arraycopy()方法进行数组之间的复制
        System.arraycopy(elementData, 0, a, 0, size);
        // 这个有点像字符串的\0操作,如果数组的长度大于列表的长度,那么就在数组最后一个元素设置为null
        if (a.length > size)
            a[size] = null;

        return a;
    }

    // Positional Access Operations
    // 位置访问操作 也就是类似get的底层实现了。 只不过这个elementData没有边界判断
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * Returns the element at the specified position in this list.
     * 检查是否范围溢出情况后,返回指定位置的元素
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }

    /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     * 用指定的元素代替此列表该位置的元素
     * 返回的是旧元素
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        // set的检测不包含负数
        // 溢出范围判断
        rangeCheck(index);
        // 获取旧元素
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * Appends the specified element to the end of this list. <br>
     * 在列表的末尾追加元素
     * 我们需要通过add()方法来看扩容机制
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */

    // 此方法为JDK7
    public boolean add(E e) {
        // 增加修改列表的次数modCount
        // 扩容先直接ensureCapacityInternal(size + 1);
        ensureCapacityInternal(size + 1);  // Increments modCount!!  JDK11移除了ensureCapacityInternal
        //ensureCapacityInternal size+1 表示最少使用容量为列表当前的size+1
        // 尾部添加这个元素 时间复杂度O(1)
        elementData[size++] = e;
        // 返回添加成功
        return true;
    }

    /**
     *
     * 在指定位置添加元素 <br>
     * 将index位置后面的元素整体往后挪动一位，再用element覆盖index处的元素
     * 时间复杂度为O(n-i)
     * <br>
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        //包括负数检测
        rangeCheckForAdd(index);

        // 先扩容，保证大小
        ensureCapacityInternal(size + 1);  // Increments modCount!!

        /*
         * 从哪里来：以index为起点，开始拷贝elementData数组中的数组
         * 到哪里去：以index + 1为起点，将数据拷贝到elementData数组中
         * 走多远：拷贝size - index个元素
         */
        // 自己复制自己
        // 后移的实现是通过System.arraycopy实现的,基于原数组上
        // 确定了当前的index位置,当前的elementData原数组, 将index位置开始的数据都copy到elementData,Dest目的数组去。操作的次数、长度为当前列表的size-index也就是index后面那个范围
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        //set index位置的元素,size也+1
        elementData[index] = element;
        size++;
    }

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     * 删除指定位置的列表元素
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        // 范围检测 并不包含负数
        rangeCheck(index);
        // 因为删除元素会改变列表的长度,因此modCount++
        modCount++;
        // 获取index位置的元素 (像set列表一样 不过set不需要修正modCount)
        E oldValue = elementData(index);

        // 要移动的元素数量,也就是当前位置包括当前位置后的元素都要往前移动 因此是size-index-1
        int numMoved = size - index - 1;
        // 如果是最后一个元素,比如size是3,index为2,那么numMoved = 3-2-1 = 0 相当于不用移动,直接跳过下面的if判断设置index元素为null即可
        // 如果是最后一个元素，则不需要做复制操作，直接删除就好
        if (numMoved > 0) {
            // 将需要删除位置后面的元素直接往前面移动一位
            // 原数组index+1位置开始的元素开始一个一个复制,复制数量为numMoevd,复制的目的地为index位置开始放
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        }
        // 将数组元素设置为null后让GC去回收
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

    /**
     * 移除操作，使用equals方法判断元素是否相等。
     * 当元素为null时，删除列表中第一个为null的元素。 <br>
     *
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {

        if (o == null) { // Object数组是支持存入null的,因此如果是null类型就删除第一个遇到的null
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) { // 判断到第一个元素为null后,直接快速删除
                    fastRemove(index); //在这里我们index是保证合法的,因此我们不需要它返回值以及检测index的范围是否合法
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) { // 通过o.equals来判断对象是否相同
                    fastRemove(index);
                    return true;
                }
        }
        // 如果传入要删除的对象不存在该列表,就返回false
        return false;
    }

    /*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     * 私有remove方法,跳过边界检测并且不返回值的删除
     */
    private void fastRemove(int index) {
        //实际上这个是类似remove方法的私有方法,相对于remove它不用检测边界rangeCheck(),以及返回oldValue
        modCount++; // 修改次数加1 ,因为会让List的长度发生变化
        int numMoved = size - index - 1;
        if (numMoved > 0) {
            // 将index后面的元素往前移动一格
            System.arraycopy(elementData, index + 1, elementData, index, numMoved);
        }
        elementData[--size] = null; // clear to let GC do its work
    }

    /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     * 清空列表中所有元素
     *
     */
    public void clear() {
        // 因为涉及元素数量变动,因此modCount++
        modCount++;
        //一个for循环将所有元素设置为null,交给gc回收
        // clear to let GC do its work
        for (int i = 0; i < size; i++) //其实我觉得可以改良一个ArrayList,也就是用lambda使得这里并行,仅限于大容量ArrayList考虑。但可能会有线程开销。
            elementData[i] = null;

        // size设置为0
        size = 0;
    }

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the
     * specified collection's Iterator.  The behavior of this operation is
     * undefined if the specified collection is modified while the operation
     * is in progress.  (This implies that the behavior of this call is
     * undefined if the specified collection is this list, and this
     * list is nonempty.)
     * 将指定集合的所有元素追加到此列表的末尾
     * 如果传入的集合在addAll的时候被修改了,会出现undefined情况(这意味着传入的Collection是非空的)
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) { //支持E相同类型或者其子类加进来,这样方便这些类型最终可以转型为E
        // 将集合转换为数组类型
        Object[] a = c.toArray();
        // 获取数组的长度
        int numNew = a.length;
        // 这个就是当前List要添加的容量数量
        ensureCapacityInternal(size + numNew);  // Increments modCount
        // 从a数组的index:0的元素开始一个一个复制到elementData的index:size中,要复制的数量为numNew个
        System.arraycopy(a, 0, elementData, size, numNew);
        // 当前List的size进一步调整(有ensureCapacityInternal的都要改动size,增删数据的时候就想想了)
        size += numNew;
        // 返回numNew的数量, 如果不为空,肯定是添加成功了的
        return numNew != 0;
    }

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     * 将指定集合中的所有元素插入到此列表中，从指定的位置开始。
     * 新元素将按照指定集合的迭代器返回的顺序出现在列表中。
     * 这个addAll的方法,就相对上面那个方法多了一个后移位置的操作, 要移动index后的所有元素,后退一位。
     *
     * @param index index at which to insert the first element from the
     *              specified collection
     * @param c collection containing elements to be added to this list
     * @return <tt>true</tt> if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);

        Object[] a = c.toArray();
        int numNew = a.length;

        // 先进行扩容
        ensureCapacityInternal(size + numNew);  // Increments modCount

        // 相对于普通的addAll(Collection)多出的移动位置
        int numMoved = size - index;

        // 大于0表示需要在列表中间插入元素，则需要把 index 后的元素往后面移动
        if (numMoved > 0) {
            //如果插入的位置不是尾部,那么就index的位置就后移到index+numNew的位置
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        }

        // 等于0就直接将新列表的元素在原有列表后进行追加
        System.arraycopy(a, 0, elementData, index, numNew);

        size += numNew;

        return numNew != 0;
    }

    /**
     * Removes from this list all of the elements whose index is between
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
     * Shifts any succeeding elements to the left (reduces their index).
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     * 移除所有在fromIndex与toIndex之前的所有元素。 也就是(fromIndex,toIndex]
     * 将任何后续元素向左移动(减少其索引index)
     * 这个调用通过 toIndex-fromIndex缩短列表
     * 如果toIndex==fromIndex,这个操作就是没有副作用(因为不存在(fromIndex,toIndex]的数字
     *
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *         {@code toIndex} is out of range
     *         ({@code fromIndex < 0 ||
     *          fromIndex >= size() ||
     *          toIndex > size() ||
     *          toIndex < fromIndex})
     * // 这里对fromIndex与toIndex是有rangeCheck的(上界与下界)
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++; //范围移除
        int numMoved = size - toIndex;

        // 直接将toIndex之后的元素移动到fromIndex之后(也就是元素列表后续的元素都往前移动(我们中间挖了一堆元素走,后面的肯定要跟上,保持连续性))
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);

        // clear to let GC do its work
        // 将列表多余的空位全部赋值为null
        // 因为后面已经往前移动了,会留下一堆无用元素的引用,要将它们设置为null
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        // 涉及元素数量变动,size要变化
        size = newSize;
    }

    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     * 判断给定的index是否在范围内,如果不在,就抛出一个运行时异常。
     * 这个方法并不检测负index。
     * 负数index总是在array访问之前就会被调用,当出现负数就会抛出ArrayIndexOutOfBoundsException
     * rangeCheck()边界判断,判断index是否大于size
     */
    private void rangeCheck(int index) {
        //如果index >= size
        if (index >= size)
            //IndexOutOfBoundsException
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * A version of rangeCheck used by add and addAll.
     * 用来检查根据add与addAll的index
     */
    private void rangeCheckForAdd(int index) {
        // 这里包括了负数检测
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    /**
     * Constructs an IndexOutOfBoundsException detail message.
     * Of the many possible refactorings of the error handling code,
     * this "outlining" performs best with both server and client VMs.
     * 构造IndexOutOfBoundsException的详细信息
     * 在错误处理代码的许多可能的重构中,这种outlining在服务器和客户端虚拟机上都表现的不错
     */

    private String outOfBoundsMsg(int index) {
        //输出Index多少，Size多少
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 从此列表中移除包含在指定集合中的所有元素
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     *
     * @param c collection containing elements to be removed from this list
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean removeAll(Collection<?> c) {
        // 判断传入的Collection是否为空
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

    /**
     * Retains only the elements in this list that are contained in the
     * specified collection.  In other words, removes from this list all
     * of its elements that are not contained in the specified collection.
     *
     * @param c collection containing elements to be retained in this list
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean retainAll(Collection<?> c) {
        // 相当于removeAll的取反,也就是List保留c的元素,除此之外的都删掉
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
    // complement是否为保留的意思
    private boolean batchRemove(Collection<?> c, boolean complement) {
        // 下面我们把参数称为参数数组，调用数组称为原数组
        // 常量elementData 感觉这个final只是为了优化吧 它的index是可变的
        final Object[] elementData = this.elementData; // 原集合
        // r,w
        int r = 0, w = 0;
        // 修改状态
        boolean modified = false;
        try {
            for (; r < size; r++) { // size原集合长度
                /*
                 * 假设第一次循环列表不包含某个元素，开始时：r=0，w=0，结束时：r=1，w=1
                 * 如果第二次循环列表包含了某个元素，则结束时：r=2，w=1，这个时候 elementData[1] 包含了某个元素
                 * 假设第三次循环列表不包含某个元素，则会将 elementData[r=2] 的元素赋值给 elementData[w=1]，也就是将前一次循环相同的元素给去掉了
                 * 依次类推
                 */
                // 如果指定列表中不包含某个元素
                // removeAll的话为false,retainAll为true
                if (c.contains(elementData[r]) == complement) { //如果传入的集合存在该元素且要保留(true)
                    elementData[w++] = elementData[r]; //这里没有动及到数组的长短,所以不会有modCount的记录
                }
                // if (c.contains(elementData[r]) == false,removeAll情况,如果不包含 r位置的元素)
                // 因为complement == false。 所以,参数数组中不包含原数组指定位置的数据时,就将原数组r位置的数据覆盖掉w位置的数据,r位置的数据不变,w自增,r自增
                // 将不包含的数据设置到w,并且w++
                // 如果是包含的话,将包含数据设置到w,w++
                // 其实这个就是一个双向选择,一对双指针,根据complement的情况,来选择留下的数据,留下的数据则会放到w中,w的位置会+1,r永远比w大,当不触发if,r与w的距离又将永久增加1格
            }
        } finally { //最终
            // Preserve behavioral compatibility with AbstractCollection,
            // 保持与AbstarctCollection的行为兼容性,除非c.contains抛出异常
            // even if c.contains() throws.
            /*
             * 只有在抛出异常的时候 r 才不等于 size
             * 这个是为了保证即使抛出异常，元素也不受影响
             */
            if (r != size) { //r一般情况会等于size,只有contains出问题了才会不等于size,这时候数组r位置开始的数据复制到数组w开始的位置上
                // (按照上面的过程,就会筛选出保留或者不保留的数据,现在由于出现了异常,上面for循环的r还没走到size的位置,但走不下去了,只能将没有处理的数据都放在筛选过的数据后面)
                System.arraycopy(elementData, r, elementData, w, size - r);
                // w为已处理的数据,这时候就要加上异常inedx后的数量
                w += size - r;
            }
            // 将最后相同的元素给赋值为 null，也就是去掉相同的元素
            if (w != size) { //w!=size,意味着数组有多余的空间,要对它设置null,减少内存使用
                // clear to let GC do its work
                for (int i = w; i < size; i++) { //从w开始后的数据都是没必要存在的了
                    elementData[i] = null;
                } //这里就相当于size-w次循环,因为有size-w次设置null,所以集合修改次数要增加size-w次。
                //modCount 从父类AbstractList继承过来的变量,作用是记录着集合修改次数
                modCount += size - w; // 集合修改次数,w后面的元素都是多余的了
                size = w; //最终列表的长度就是w
                modified = true; //修改完毕
            }
        }
        return modified;
    }

    /**
     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
     * is, serialize it).
     * 保存ArrayList实体传递到stream (序列化化ArrayList)
     * @serialData The length of the array backing the <tt>ArrayList</tt>
     *             instance is emitted (int), followed by all of its elements
     *             (each an <tt>Object</tt>) in the proper order.
     * 传递emitted支持ArrayList实例数组的长度,后跟着所有元素(对象)的正确书匈奴
     */
    // ObjectOutputStream, 对象流
    private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{
        // 调用writeObject后,当前ArrayList实例的状态会被hold住,同时当前ArrayList的线程也被hold住,直到该writeObject方法结束才释放SerialCallBackContext
        // Write out element count, and any hidden stuff
        // 写出元素计数和任何隐藏的东西
        int expectedModCount = modCount; // 有点类似CAS

        s.defaultWriteObject();

        // Write out size as capacity for behavioural compatibility with clone()
        // 将大小写为兼容clone()行为的size
        s.writeInt(size);

        // Write out all elements in the proper order.
        // 按正确的顺序写出所有元素
        for (int i=0; i<size; i++) {
            s.writeObject(elementData[i]);
        }
        // 这证明在写出ObjectOutputStream 序列化过程有线程修改了ArrayList的长度(增加/删除列表长度)
        if (modCount != expectedModCount) {
            // 因此抛出ConcurrentModificationException
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
     * deserialize it).
     * 从stream中取出重组ArrayList对象(反序列化)
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        elementData = EMPTY_ELEMENTDATA; //反序列化,先初始化集合为0

        // Read in size, and any hidden stuff
        // 读取非static方法以及非transient方法
        s.defaultReadObject();

        // Read in capacity
        // 读取容量
        s.readInt(); // ignored

        // 如果size > 0
        if (size > 0) {
            // be like clone(), allocate array based upon size not capacity
            // 根据size来扩容
            ensureCapacityInternal(size);
            // 初始化对象数组
            Object[] a = elementData;
            // Read in all elements in the proper order.
            // 按正确的顺序读取所有元素
            for (int i=0; i<size; i++) {
                a[i] = s.readObject();
            }
        }
    }

    /**
     * Returns a list iterator over the elements in this list (in proper
     * sequence), starting at the specified position in the list.
     * The specified index indicates the first element that would be
     * returned by an initial call to {@link ListIterator#next next}.
     * An initial call to {@link ListIterator#previous previous} would
     * return the element with the specified index minus one.
     * listIterator可以指定List开始的index去取,也就是ListIterator从index位置开始按正确顺序返回list所有元素的迭代器
     * 第一杆元素应该要next而不是previous,previous会出现负1索引
     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * Returns a list iterator over the elements in this list (in proper
     * sequence).
     * 按正确顺序返回一个该列表元素的list iterator;(列表迭代器,快速失败)
     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @see #listIterator(int)
     */
    public ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     * 按正确顺序返回此列表中元素的迭代器
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     * 返回的iterator是快速失败机制
     * @return an iterator over the elements in this list in proper sequence
     * 将以正确顺序返回此列表中元素的迭代器
     * 获取ArrayList的iterator  也就是返回一个private的Itr类的实例
     */
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     * 一个AbstarctList.Itr的优化版本
     */
    private class Itr implements Iterator<E> {
        /**
         * 本地遍历的当前位置
         */
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        /**
         * 应该被修改的次数
         */
        int expectedModCount = modCount;

        /**
         * 如果当前的位置跟元素的大小不相等，则表示还有元素没有遍历完
         */
        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            // 当多个线程修改时，会产生fail-fast的原因就在这里
            checkForComodification();
            int i = cursor;
            if (i >= size) {
                throw new NoSuchElementException();
            }
            Object[] elementData = ArrayList.this.elementData;

            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0) {
                throw new IllegalStateException();
            }

            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                // 之所以删除列表中的元素必须调用迭代器中的remove()才不会反生fail-fast异常的原因就在这里
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     * 一个AbstractList.ListItr的优化版本
     */
    private class ListItr extends Itr implements ListIterator<E> {

        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        @SuppressWarnings("unchecked")
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

    /**
     * Returns a view of the portion of this list between the specified
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
     * {@code fromIndex} and {@code toIndex} are equal, the returned list is
     * empty.)  The returned list is backed by this list, so non-structural
     * changes in the returned list are reflected in this list, and vice-versa.
     * The returned list supports all of the optional list operations.
     * 返回当前List的View视图,这个视图范围是List的(fromIndex,toIndex]
     * 如果fromIndex==toIndex,返回的subList视图就为空
     *
     * <p>This method eliminates the need for explicit range operations (of
     * the sort that commonly exist for arrays).  Any operation that expects
     * a list can be used as a range operation by passing a subList view
     * instead of a whole list.  For example, the following idiom
     * removes a range of elements from a list:
     * <pre>
     *      list.subList(from, to).clear();
     * </pre>
     * Similar idioms may be constructed for {@link #indexOf(Object)} and
     * {@link #lastIndexOf(Object)}, and all of the algorithms in the
     * {@link Collections} class can be applied to a subList.
     *
     * <p>The semantics of the list returned by this method become undefined if
     * the backing list (i.e., this list) is <i>structurally modified</i> in
     * any way other than via the returned list.  (Structural modifications are
     * those that change the size of this list, or otherwise perturb it in such
     * a fashion that iterations in progress may yield incorrect results.)
     *
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws IllegalArgumentException {@inheritDoc}
     */

    public List<E> subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList(this, 0, fromIndex, toIndex);
    }

    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > size)
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
    }

    private class SubList extends AbstractList<E> implements RandomAccess {
        private final AbstractList<E> parent;
        private final int parentOffset;
        private final int offset;
        int size;

        SubList(AbstractList<E> parent,
                int offset, int fromIndex, int toIndex) {
            this.parent = parent;
            this.parentOffset = fromIndex;
            this.offset = offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = ArrayList.this.modCount;
        }

        public E set(int index, E e) {
            rangeCheck(index);
            checkForComodification();
            E oldValue = ArrayList.this.elementData(offset + index);
            ArrayList.this.elementData[offset + index] = e;
            return oldValue;
        }

        public E get(int index) {
            rangeCheck(index);
            checkForComodification();
            return ArrayList.this.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return this.size;
        }

        public void add(int index, E e) {
            rangeCheckForAdd(index);
            checkForComodification();
            parent.add(parentOffset + index, e);
            this.modCount = parent.modCount;
            this.size++;
        }

        public E remove(int index) {
            rangeCheck(index);
            checkForComodification();
            E result = parent.remove(parentOffset + index);
            this.modCount = parent.modCount;
            this.size--;
            return result;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            parent.removeRange(parentOffset + fromIndex,
                               parentOffset + toIndex);
            this.modCount = parent.modCount;
            this.size -= toIndex - fromIndex;
        }

        public boolean addAll(Collection<? extends E> c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;

            checkForComodification();
            parent.addAll(parentOffset + index, c);
            this.modCount = parent.modCount;
            this.size += cSize;
            return true;
        }

        public Iterator<E> iterator() {
            return listIterator();
        }

        public ListIterator<E> listIterator(final int index) {
            checkForComodification();
            rangeCheckForAdd(index);
            final int offset = this.offset;

            return new ListIterator<E>() {
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = ArrayList.this.modCount;

                public boolean hasNext() {
                    return cursor != SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }

                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

                @SuppressWarnings("unchecked")
                public void forEachRemaining(Consumer<? super E> consumer) {
                    Objects.requireNonNull(consumer);
                    final int size = SubList.this.size;
                    int i = cursor;
                    if (i >= size) {
                        return;
                    }
                    final Object[] elementData = ArrayList.this.elementData;
                    if (offset + i >= elementData.length) {
                        throw new ConcurrentModificationException();
                    }
                    while (i != size && modCount == expectedModCount) {
                        consumer.accept((E) elementData[offset + (i++)]);
                    }
                    // update once at end of iteration to reduce heap write traffic
                    lastRet = cursor = i;
                    checkForComodification();
                }

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        ArrayList.this.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = ArrayList.this.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (expectedModCount != ArrayList.this.modCount)
                        throw new ConcurrentModificationException();
                }
            };
        }

        public List<E> subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList(this, offset, fromIndex, toIndex);
        }

        private void rangeCheck(int index) {
            if (index < 0 || index >= this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (ArrayList.this.modCount != this.modCount)
                throw new ConcurrentModificationException();
        }

        public Spliterator<E> spliterator() {
            checkForComodification();
            return new ArrayListSpliterator<E>(ArrayList.this, offset,
                                               offset + this.size, this.modCount);
        }
    }
    /**JDK1.8才有的lambda forEach*/
    @Override
    public void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    /**
     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
     * list.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
     * Overriding implementations should document the reporting of additional
     * characteristic values.
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new ArrayListSpliterator<>(this, 0, -1, 0);
    }

    /** Index-based split-by-two, lazily initialized Spliterator */
    static final class ArrayListSpliterator<E> implements Spliterator<E> {

        /*
         * If ArrayLists were immutable, or structurally immutable (no
         * adds, removes, etc), we could implement their spliterators
         * with Arrays.spliterator. Instead we detect as much
         * interference during traversal as practical without
         * sacrificing much performance. We rely primarily on
         * modCounts. These are not guaranteed to detect concurrency
         * violations, and are sometimes overly conservative about
         * within-thread interference, but detect enough problems to
         * be worthwhile in practice. To carry this out, we (1) lazily
         * initialize fence and expectedModCount until the latest
         * point that we need to commit to the state we are checking
         * against; thus improving precision.  (This doesn't apply to
         * SubLists, that create spliterators with current non-lazy
         * values).  (2) We perform only a single
         * ConcurrentModificationException check at the end of forEach
         * (the most performance-sensitive method). When using forEach
         * (as opposed to iterators), we can normally only detect
         * interference after actions, not before. Further
         * CME-triggering checks apply to all other possible
         * violations of assumptions for example null or too-small
         * elementData array given its size(), that could only have
         * occurred due to interference.  This allows the inner loop
         * of forEach to run without any further checks, and
         * simplifies lambda-resolution. While this does entail a
         * number of checks, note that in the common case of
         * list.stream().forEach(a), no checks or other computation
         * occur anywhere other than inside forEach itself.  The other
         * less-often-used methods cannot take advantage of most of
         * these streamlinings.
         */

        private final ArrayList<E> list;
        private int index; // current index, modified on advance/split
        private int fence; // -1 until used; then one past last index
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
                             int expectedModCount) {
            this.list = list; // OK if null unless traversed
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            ArrayList<E> lst;
            if ((hi = fence) < 0) {
                if ((lst = list) == null)
                    hi = fence = 0;
                else {
                    expectedModCount = lst.modCount;
                    hi = fence = lst.size;
                }
            }
            return hi;
        }

        public ArrayListSpliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator<E>(list, lo, index = mid,
                                            expectedModCount);
        }

        public boolean tryAdvance(Consumer<? super E> action) {
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;
                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi, mc; // hoist accesses and checks from loop
            ArrayList<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null && (a = lst.elementData) != null) {
                if ((hi = fence) < 0) {
                    mc = lst.modCount;
                    hi = lst.size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (lst.modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

}
